//
//  MyNickNameViewController.m
//  eshow
//
//  Created by Hisoka on 15/11/17.
//  Copyright © 2015年 Hisoka. All rights reserved.
//

#import "MyNickNameViewController.h"

static int textFieldLength = 8;

@interface MyNickNameViewController ()<UITextFieldDelegate>

@property (nonatomic, strong) UITextField *nickNameTF;

@end

@implementation MyNickNameViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self customizeBackItem];
    self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self setStyle];
}

- (void) viewWillDisappear:(BOOL)animated {
    [self textFieldDealloc];
}

- (void) setStyle {
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    
    self.navigationItem.title = @"编辑昵称";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存"
                                                                              style:UIBarButtonItemStyleDone
                                                                             target:self
                                                                             action:@selector(setUserInfoAction)];
    self.navigationItem.rightBarButtonItem.tintColor = ORANGE_COLOR;
    
    self.view.backgroundColor = GRAY_COLOR;
    
    UILabel *nickNameLB = [UILabel newAutoLayoutView];
    [self.view addSubview:nickNameLB];
    
    [nickNameLB autoPinToTopLayoutGuideOfViewController:self withInset:0];
    [nickNameLB autoAlignAxis:ALAxisVertical toSameAxisOfView:self.view];
    [nickNameLB autoSetDimensionsToSize:CGSizeMake(ScreenWidth, 50)];
    nickNameLB.text = TEXT_NICKNAME;
    nickNameLB.backgroundColor = WHITE_COLOR;
    
    self.nickNameTF = [UITextField newAutoLayoutView];
    [self.view addSubview:_nickNameTF];
    
    [_nickNameTF autoAlignAxis:ALAxisHorizontal toSameAxisOfView:nickNameLB];
    [_nickNameTF autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:nickNameLB withOffset:80];
    [_nickNameTF autoSetDimensionsToSize:CGSizeMake(ScreenWidth - 100, 40)];
    _nickNameTF.text = [[[TMCache sharedCache] objectForKey:@"userInfo"] objectForKey:@"nickname"];
    _nickNameTF.placeholder = @"由字母或数字组成";
    _nickNameTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    _nickNameTF.returnKeyType = UIReturnKeyDone;
    _nickNameTF.delegate = self;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFiledEditChanged:) name:@"UITextFieldTextDidChangeNotification" object:_nickNameTF];

}

-(void)textFiledEditChanged:(NSNotification *)obj{

    UITextField *textField = (UITextField *)obj.object;
    
    NSString *toBeString = textField.text;
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage];
    
    if ([lang isEqualToString:@"zh-Hans"]) {
        UITextRange *selectRange = [textField markedTextRange];
        UITextPosition *position = [textField positionFromPosition:selectRange.start offset:0];
        if (!position) {
            if (toBeString.length > textFieldLength) {
                textField.text = [toBeString substringToIndex:textFieldLength];
            }
        }else{
            
        }
    }else{
        if (toBeString.length > textFieldLength) {
            textField.text = [toBeString substringToIndex:textFieldLength];
        }
    }
    
}

-(void) textFieldDealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self
                                                   name:@"UITextFieldTextDidChangeNotification"
                                                 object:_nickNameTF];
}

- (void) setUserInfoAction {
    if (_nickNameTF.text.length <= 0) {
        [SVProgressHUD showInfoWithStatus:@"请填写昵称"];
        return;
    }
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:[[TMCache sharedCache] objectForKey:@"SSID"] forKey:@"ssid"];
    [parameters setObject:_nickNameTF.text forKey:@"nickname"];
    
    [SVProgressHUD show];
    [[HttpManager instance] requestWithMethod:@"User/upProfile"
                                   parameters:parameters
                                      success:^(NSDictionary *result) {
                                          NSDictionary *userInfoTmp = [result objectForKey:@"data"];
                                          NSString *alertText = [userInfoTmp objectForKey:@"info"];
                                          
                                          [[TMCache sharedCache] setObject:userInfoTmp forKey:@"userInfo"];
                                          
                                          [_nickNameTF resignFirstResponder];
                                          
                                          [SVProgressHUD showSuccessWithStatus:alertText maskType:SVProgressHUDMaskTypeBlack];
                                      }
                                      failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                          [SVProgressHUD showInfoWithStatus:[error localizedDescription] maskType:SVProgressHUDMaskTypeBlack];
                                      }];
}

- (BOOL) textFieldShouldReturn:(UITextField *)textField {
    if (textField == _nickNameTF) {
        [_nickNameTF resignFirstResponder];
    }
    return YES;
}

- (void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [_nickNameTF resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
